package com.cosina.mr.util;

import java.util.HashMap;
import java.util.Map;


public class PieChartData {
	
	private Map<String,Float> result;
	
	public PieChartData(Map<String,Integer> rawData){
		Map<String,Float> rawDegress = analyze(rawData);
		this.result = adjust(rawDegress);
	}
	
	public Map<String,Float> getResult(){
		return result;
	}
	
	private Map<String,Float> adjust(Map<String,Float> rawDegress) {
		float deviation = 0;
		
		while((deviation = calDeviation(rawDegress)) != 0){
			float quota = deviation/rawDegress.size();
			for(String key : rawDegress.keySet()){
				rawDegress.put(key, rawDegress.get(key) - quota);
			}
		}
		return rawDegress;
	}
	
	private float calDeviation(Map<String,Float> rawDegress){
		float total = 0;
		for(float each : rawDegress.values()){
			total += each;
		}
		int roundTotal = Math.round(total);
		return roundTotal - 360;
	}

	private Map<String,Float> analyze(Map<String,Integer> rawData){
		float total = 0;
		for(int each : rawData.values()){
			total += each;
		}
		Map<String,Float> result = new HashMap<String,Float>();
		for(String key : rawData.keySet()){
			result.put(key, rawData.get(key) * 360 /total);
		}
		return result;
	}
}
